const _ = require('lodash');
const https = require('https');
const axios = require('axios');
const fetch = require('node-fetch');
const crypto = require('crypto');

function client(baseURL) {
  const username = process.env.API_USER_NAME;
  const password = process.env.API_PASSWORD;
  const cert = process.env.API_CERT;
  const key = process.env.API_KEY;
  const passphrase = process.env.API_PASSPHRASE;
  const timeout = process.env.SOAG_TIMEOUT;
  const auth = Buffer.from(`${username}:${password}`, 'ascii').toString('base64');
  const client = axios.create({
    baseURL,
    headers: {
      Authorization: `Basic ${auth}`,

    },
    httpsAgent: new https.Agent({
      key,
      cert,
      passphrase,
      rejectUnauthorized: false,
    }),
    timeout,
  });
  return client;
}

const sadClient = client('https://soa-ch.xh3.lilly.com:8443/dev/lsad/');
exports.getUserProfile = function getUserProfile(id) {
  return sadClient.get(`Api/Employee/GetEmployeeByAccountName?accountname=${id}`);
};

exports.getUserByQuery = function getUserByQuery(query) {
  return sadClient.get(`Api/Employee/GetEmployeeByMixedQuery?query=${encodeURI(query)}`);
};

exports.getHierarchyByEmployeeID = function getUserByQuery(employeeId, yearMonthId) {
  yearMonthId = yearMonthId || new Date().toISOString().split('T')[0].replace(/-/g, '').slice(0, 6);
  return sadClient.get(`api/Org/GetHierarchyByEmployeeLillyID?lillyID=${employeeId}&yearMonth=${yearMonthId}`);
};


exports.parseUser = function parseUser(data) {
  const user = {};
  user.employeeId = !_.isEmpty(data.LillyID) ? data.LillyID : data.GlobalID;
  user.chineseName = !_.isEmpty(data.ChineseName) ? data.ChineseName : data.GlobalID;
  user.englishName = !_.isEmpty(data.ChineseName) ? data.ChineseName : data.GlobalID;
  user.email = !_.isEmpty(data.Email) ? data.Email : `${data.GlobalID}@loopback.com`;
  user.createdAt = data.CRT_DT;
  user.createdBy = data.CRT_USR;
  user.updatedAt = data.UP_DT;
  user.updateby = data.UP_USR;
  user.password = generateKey('password');
  return user;
};

function generateKey(hmacKey, algorithm, encoding) {
  algorithm = algorithm || 'sha1';
  encoding = encoding || 'hex';
  const hmac = crypto.createHmac(algorithm, hmacKey);
  const buf = crypto.randomBytes(32);
  hmac.update(buf);
  const key = hmac.digest(encoding);
  return key;
}

let gatewayUrl = 'https://gateway-np.lillyapi.com:8443/';
let gatewayID = '648940599454';

if (process.env.NODE_ENV === 'production') {
  gatewayUrl = 'https://gateway.lillyapi.com:8443/';
  gatewayID = '791974153892';
}

const awsClient = client(gatewayUrl);
const tokenClient = client(`${process.env.OPENID_ISSUER}`);

exports.getAWSCredential = async function getAWSCredential(session, bolRetry) {
  if (session.expired_date < new Date().getTime()) {
    console.log(`get refresh token:${session.refresh_token}`);

    await fetch(`${process.env.OPENID_ISSUER}/as/token.oauth2`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body:
            `client_id=${process.env.OPENID_CLIENT_ID}&client_secret=${process.env.OPENID_CLIENT_SECRET}` +
            `&grant_type=refresh_token&refresh_token=${session.refresh_token}`,
    }).then(resp => resp.json())
            .then((tokenResp) => {
              console.log(`get refresh token Result:${JSON.stringify(tokenResp)}`);
              return Promise.resolve(tokenResp);
            })
            .then((response) => {
              if (response.access_token != null) {
                const date = new Date();
                session.expired_date = date.getTime() + response.expires_in * 1000 - 5 * 60 * 1000;
                session.access_token = response.access_token;
                session.refresh_token = response.refresh_token;
              } else if (!bolRetry) {
                getAWSCredential(session, true); // give one more chance
              }
            });

       /* await tokenClient.post('/as/token.oauth2', querystring.stringify({
                client_id: process.env.OPENID_CLIENT_ID,
                client_secret:process.env.OPENID_CLIENT_SECRET,
                grant_type: 'refresh_token',
                refresh_token:session.refresh_token ,
            }))
            .catch(function (error) {
                if (error.response) {
                    console.log(error.response.data);
                }

            })
            .then((response) => {
                var date = new Date();
                session.expired_date = date.setTime(date.getTime() + response.expires_in);
                session.access_token = response.access_token;
            });
        */
  }


  console.log(`getAWSCredential  gatewayUrl:${gatewayUrl} gatewayID:${gatewayID} accessToken:${session.access_token}`);
  const dd = awsClient.get(`aws/credentials?account=${gatewayID}`, {
    headers: { Authorization: `Bearer ${session.access_token}` },
  }).catch((error) => {
    if (error.response) {
            // The request was made and the server responded with a status code
            // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
            // The request was made but no response was received
            // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
            // http.ClientRequest in node.js
      console.log(error.request);
    } else {
            // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });
  return dd;
};
